package cn.he4966.ws.wss;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

@Service
@Slf4j
public class WebSocketService {

    /**
     * 发送消息
     *
     * @param session
     * @param text
     * @return
     * @throws IOException
     */
    public void sendMsg(WebSocketSession session, String text) throws IOException {
        session.sendMessage(new TextMessage(text));
    }

    /**
     * 广播消息
     *
     * @param text
     * @return
     * @throws IOException
     */
    public void broadcastMsg(String text) throws IOException {
        Integer count = WebSocketSessionManager.sendMessageToGroup("", text);
//        for (WebSocketSession session : WebSocketSessionManager.SESSION_POOL.values()) {
//            session.sendMessage(new TextMessage(text));
//        }
    }


    /**
     * 广播消息
     *
     * @param text
     * @return
     * @throws IOException
     */
    public void broadcastMsg(String group, String text) throws IOException {
        // 根据群组筛选

        WebSocketSessionManager.sendMessageToGroup(group, text);
//        for (WebSocketSession session : WebSocketSessionManager.SESSION_POOL.values()) {
//            session.sendMessage(new TextMessage(text));
//        }
    }

    /**
     * 添加群组
     *
     * @param group
     * @param session
     */
    public static void addGroup(String group, WebSocketSession session) {
//        WebSocketSessionManager.add(group,session);
        WebSocketSessionManager.addSessionToGroup(group, session);
        System.out.println("添加群组：" + group);
    }


    /**
     * 添加群组
     *
     * @param group
     * @param text
     */
    public static Integer groupMsg(String group, String text) throws IOException {
        //获取群组里面到所有用户

        Integer count = WebSocketSessionManager.sendMessageToGroup(group, text);
        return count;

//        WebSocketSessionManager.SESSION_POOL.get(group).sendMessage(new TextMessage(text));

    }
}